<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-model="filters.orgUnitId" placeholder="请选择店铺" :org-unit-type="1" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddRoom" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAdd">创建房间</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.rooms" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="name" label="名称" min-width="320" />
      <el-table-column prop="orgUnitName" label="店铺" min-width="260" />
      <el-table-column prop="balance" label="余额(元)" width="120" :formatter="formatBalance" />
      <el-table-column prop="luckyMoney" label="返利余额(元)" width="120" :formatter="formatLuckyMoney" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="280" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
          <el-button v-if="canCharge" size="small" @click="handleCharge(scope.index, scope.row)">充值</el-button>
          <el-button size="small" @click="generateQrCode(scope.index, scope.row)">生成二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="房间信息" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item v-if="!recordId" label="店铺">
          <org-unit-select v-model="addForm.orgUnitId" placeholder="请选择店铺" :org-unit-type="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="房间充值" :visible.sync="chargeVisible" :close-on-click-modal="false" @close="chargeDialogClose">
      <el-form v-if="chargeStep===1" ref="chargeForm" :model="chargeForm" :label-width="formLabelWidth">
        <el-form-item label="房间" prop="roomName">
          <el-input v-model="chargeForm.roomName" disabled auto-complete="off" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-radio-group v-model="chargeForm.amount">
            <el-radio :label="250000" border>2500元</el-radio>
            <el-radio :label="500000" border>5000元</el-radio>
            <el-radio :label="1000000" border>10000元</el-radio>
            <el-radio v-if="canDirectCharge" :label="-1" border>自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="chargeForm.amount===-1" label="输入金额" prop="inputAmount">
          <el-input-number v-model="chargeForm.inputAmount" label="请输入金额" :precision="2" controls-position="right" />元
        </el-form-item>
        <el-form-item label="充值方式" prop="payType">
          <el-radio-group v-model="chargeForm.payType">
            <el-radio :label="1" border>微信</el-radio>
            <el-radio :label="2" border>支付宝</el-radio>
            <el-radio v-if="canDirectCharge" :label="3" border>管理员直充</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div v-if="chargeStep===2" class="qr-code-container">
        <p>扫描二维码完成充值</p>
        <qrcode :size="156" :text="chargeCode" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="chargeStep===1" @click="prepareOrder">充值</el-button>
        <el-button @click="chargeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="房间二维码" :visible.sync="qrCodeVisible" :close-on-click-modal="false">
      <div class="qr-code-container">
        <qrcode :size="156" :text="qrContent" />
        <p>{{ qrInfo.name }}</p>
        <p>{{ qrInfo.address }}</p>
        <p>失效日期：{{ qrInfo.expiredTime }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, saveRoom, modifyRoom } from '@/api/rooms'
import { roomQrCodeInfo } from '@/api/qr-code'
import { prepareOrder, queryOrder, closeOrder } from '@/api/charge-records'
import OrgUnitSelect from '../components/org-unit-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Qrcode from '@/components/qrcode'
import util from '@/utils/util.js'

export default {
  name: 'Rooms',
  components: { Pagination, Qrcode, OrgUnitSelect },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        orgUnitId: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      qrCodeVisible: false,
      qrInfo: {
        name: '',
        address: '',
        expiredTime: ''
      },
      qrContent: '{}',

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: 0,
      addForm: {
        name: '',
        orgUnitId: null
      },
      // 充值
      timer: null,
      chargeVisible: false,
      chargeStep: 1,
      chargeCode: '',
      chargeOrderId: null,
      chargeForm: {
        roomId: null,
        roomName: '',
        amount: 0,
        inputAmount: 0,
        payType: 1
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn']),
    canAddRoom() {
      const roles = this.userInfo.roles || []
      if (roles.indexOf('Admin') !== -1) {
        return true
      }
      if (roles.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 2) {
          // 加盟商
          return true
        }
      }
      return false
    },
    canCharge() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1 || roles.indexOf('Manager') !== -1 || roles.indexOf('ShopManager') !== -1
    },
    canDirectCharge() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    formatBalance(row) {
      return util.currency.format(row.balance)
    },
    formatLuckyMoney(row) {
      return util.currency.format(row.luckyMoney)
    },
    checkColumn(col) {
      if (this.dynamicColumn.rooms.hasOwnProperty(col)) {
        return this.dynamicColumn.rooms[col].show
      }
      return true
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listRoom(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.recordId = null
      this.addForm.name = ''
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.name = row.name
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            if (this.recordId) {
              this.doEdit()
            } else {
              this.doAdd()
            }
          })
        }
      })
    },
    doAdd() {
      saveRoom({ ...this.addForm }).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    doEdit() {
      modifyRoom(this.recordId, this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '保存失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    generateQrCode(index, row) {
      this.qrCodeVisible = true
      roomQrCodeInfo(row.id).then(({ success, message, data }) => {
        if (success) {
          this.qrInfo.name = data.name
          this.qrInfo.address = (data.addr || '') + (data.detailAddress || '')
          this.qrInfo.expiredTime = data.expiredTime
          this.qrContent = JSON.stringify(data)
        } else {
          this.$message({
            message: message || '查询二维码信息失败',
            type: 'error'
          })
        }
      }, () => {
        this.qrCodeVisible = false
      })
    },
    handleCharge(index, row) {
      this.chargeStep = 1
      this.chargeVisible = true
      this.chargeForm.amount = 10000
      this.chargeForm.payType = 1
      this.chargeForm.roomName = row.name
      this.chargeForm.roomId = row.id
      this.chargeForm.inputAmount = 0
    },
    prepareOrder() {
      const param = { roomId: this.chargeForm.roomId, amount: this.chargeForm.amount, payType: this.chargeForm.payType }
      if (param.amount === -1) { // 自定义充值的情况
        const amt = Number.parseFloat(this.chargeForm.inputAmount)
        param.amount = amt * 100
      }
      prepareOrder(param).then(({ success, message, data }) => {
        if (success) {
          if (this.chargeForm.payType === 3) {
            const { id } = data || {}
            this.chargeOrderId = id
            this.timeoutRunner()
          } else {
            this.chargeStep = 2
            const { payCode, id } = data || {}
            this.chargeCode = payCode
            this.chargeOrderId = id
            this.closeMyTimer()
            this.timer = setInterval(this.timeoutRunner, 1000) // 每秒查询一下订单状态
          }
        } else {
          this.$message({
            message: message || '充值订单请求失败',
            type: 'error'
          })
        }
      }, () => {
        this.chargeVisible = false
      })
    },
    timeoutRunner() {
      queryOrder(this.chargeOrderId).then(({ success, message, data }) => {
        if (success) {
          if (data.state === 2) { // 已支付
            this.$message({
              message: '充值成功',
              type: 'success'
            })
            this.chargeOrderId = null
            this.chargeVisible = false
            this.loadPageList()
          } else if (data.state === 3) { // 已关闭
            this.$message({
              message: '订单已关闭',
              type: 'error'
            })
            this.chargeOrderId = null
            this.chargeVisible = false
          }
        } else {
          this.$message({
            message: message || '充值订单请求失败',
            type: 'error'
          })
        }
      })
    },
    chargeDialogClose() {
      this.closeMyTimer()
      if (this.chargeOrderId) {
        closeOrder(this.chargeOrderId).then(({ success, message }) => {
          if (success) {
            this.$message({
              message: message || '订单已关闭',
              type: 'success'
            })
            this.chargeVisible = false
          } else {
            this.$message({
              message: message || '关闭订单失败',
              type: 'error'
            })
          }
        })
      }
    },
    closeMyTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-code-container {
  text-align: center;
  img {
    display: inline-block;
  }
}
</style>
